package com.zjsos.dao;

import org.hibernate.*;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;


public class BaseDao{

	private	SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}

	@Transactional(rollbackFor = Exception.class)
	public <T> Serializable save(T t) throws Exception {
		return getSession().save(t);
	}
	@Transactional(rollbackFor = Exception.class)
	public <T> void delete(T t) throws Exception {
		getSession().delete(t);
	}

	@Transactional(rollbackFor = Exception.class)
	public <T> T update(T t) throws Exception {
		getSession().update(t);
		return t;
	}

	public <T> List<T> findPageSqlDto(Class<T> clz, String sql, int first, int max, Object obj) throws Exception {

		SQLQuery query = (SQLQuery) getSession().createSQLQuery(sql);
		setParamets(obj, query);
		query.setFirstResult(first);
		query.setMaxResults(max);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return (List<T>) query.list();
	}

	private void setParamets(Query query, Object[] obj, int index){
		for(Object o:(Object[])obj){
			if(o instanceof Object[]){
				setParamets(query,(Object[]) o, index);
			}else{
				query.setParameter(index,o);
			}
			index++;
		}
	}

	private void setParamets(Object obj,Query query){
		if(obj instanceof Map){
			query.setProperties((Map<String,Object>)obj);
		}else if(obj instanceof Object[]){
			setParamets(query, (Object[]) obj,0);
		}
	}
}
